import 'package:flutter/material.dart';

import '../../pojo/Result.dart';
import '../../res/TestTradeData.dart'; // 引入 TestTradeData
import '../../viewModels/UserViewModel.dart';

class Mall extends StatelessWidget {
  const Mall({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("积分商城"),
      ),
      body: const _MallBody(),
    );
  }
}

class _MallBody extends StatefulWidget {
  const _MallBody({super.key});

  @override
  State<_MallBody> createState() => _MallBodyState();
}

class _MallBodyState extends State<_MallBody> {

  String userActivityIntegral = "----";

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _loadUserActivityIntegral();
  }

  void _loadUserActivityIntegral() async {
    Result result = await UserViewModel().getUserActivityIntegral();
    if(result.code == 1){
      setState(() {
        userActivityIntegral = result.data.toString();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
      child: Center(
          child: Column(
            children: [
              SizedBox(
                width: double.infinity,
                child: _buildPointsCard(),
              ),
              Expanded(
                child: ConstrainedBox(
                  constraints: const BoxConstraints(maxWidth: 800),
                  child: ListView(
                    padding: const EdgeInsets.all(16.0),
                    children: [
                      const SizedBox(height: 16.0),
                      _buildProductGrid(),
                    ],
                  ),
                ),
              )
            ],
          )
      ),
    );
  }

  Widget _buildPointsCard() {
    return Card(
      elevation: 4.0,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12.0),
      ),
      color: Theme.of(context).colorScheme.primary,
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '我的积分',
              style: TextStyle(
                  fontSize: 18.0,
                  fontWeight: FontWeight.bold,
                  color: Colors.white
              ),
            ),
            const SizedBox(height: 8.0),
            Text(
              '$userActivityIntegral 积分',
              style: const TextStyle(
                fontSize: 24.0,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
            const SizedBox(height: 16.0),
          ],
        ),
      ),
    );
  }

  Widget _buildProductGrid() {
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        crossAxisSpacing: 16.0,
        mainAxisSpacing: 16.0,
        childAspectRatio: 1/1.7,
      ),
      itemCount: testTradeData.length, // 使用 testTradeData 的长度
      itemBuilder: (context, index) {
        final product = testTradeData[index]; // 获取当前商品数据
        final userIntegral = int.tryParse(userActivityIntegral) ?? 0;
        final productPrice = int.tryParse(product['price'].toString()) ?? 0;
        final isEnoughIntegral = userIntegral >= productPrice;

        return Card(
          elevation: 4.0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12.0),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: ClipRRect(
                  borderRadius: const BorderRadius.vertical(
                    top: Radius.circular(12.0),
                  ),
                  child: Image.network(
                    product['imageUrl'], // 使用商品图片 URL
                    fit: BoxFit.cover,
                    width: double.infinity,
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      product['name'], // 使用商品名称
                      style: const TextStyle(
                        fontSize: 16.0,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 4.0),
                    Text(
                      '${product['price']} 积分', // 使用商品价格
                      style: const TextStyle(
                        fontSize: 14.0,
                        color: Colors.orange,
                      ),
                    ),
                    const SizedBox(height: 8.0),
                    ElevatedButton(
                      onPressed: isEnoughIntegral ? () {
                        showDialog(
                            context: context,
                            builder: (context) {
                              return AlertDialog(
                                  title: const Text('兑换提示'),
                              content: const Text('确定要兑换该商品吗？'),
                              actions: [
                              TextButton(
                              onPressed: () {
                              Navigator.of(context).pop();
                              },
                              child: const Text('取消'),
                              ),
                              TextButton(
                              onPressed: () {
                              Navigator.of(context).pop();
                              },
                              child: const Text('确定'),
                              )
                              ]);
                            }
                        );
                      } : null,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: isEnoughIntegral ? null : Colors.grey,
                      ),
                      child: Text(isEnoughIntegral ? '立即兑换' : '积分不足'),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}

